﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;


namespace UnionPay4WP
{
    public class XmlResponseParser
    {
        string SUCCESSCODE = errorTranslator.successCode();
        public bool parse(string msg,out int nextUri)
        {
            bool result=false;
            nextUri = 0;//todo ,set a default xaml
            try
            {
                XElement xmlResponse = XElement.Parse(msg);
                try
                {
                    ServerResponseVars.MsgResponseCode = xmlResponse.Element("msgResponseCode").Value;
                    ServerResponseVars.TransactionType = xmlResponse.Element("cupMobile").Element("transaction").Attribute("type").Value;
                }
                finally {
                    ServerResponseVars.MsgResponseCode = xmlResponse.Element("msgResponseCode").Value;
                    ServerResponseVars.TransResponseCode = xmlResponse.Element("cupMobile").Element("transaction").Element("transResponseCode").Value;               
                }
                switch (ServerResponseVars.TransactionType)
                {
                    case  "PayInit.PARsp":
                        result= payInit(xmlResponse);
                        nextUri =0;
                        break;
                    case "BankSupportEnquiry.PARsp":
                        nextUri = 5;//"bankListPivot";//"/UnionPay4WP;component/BankList.xaml";
                        result = bankSupportEnquiry(xmlResponse);
                        break;
                    case "CardInfoEnquiry.PARsp":
                        if (result = cardInfoEnquiry(xmlResponse))
                        {
                            if ("CreditCard"==ServerResponseVars.cardType)
                            {
                                nextUri = 2;// "CardInfoPivot";//"/UnionPay4WP;component/CardInfo.xaml";
                            }
                            else
                            {
                                nextUri =3;//"CardInfo2Pivot";//"/UnionPay4WP;component/CardInfo2.xaml";
                            }
                        }
                        break;
                    //case "CardTransInfoEnquiry.PARsp":
                    //    nextUri = 7;
                    //    result = CardTransInfoEnquiry(xmlResponse);
                    case "SMSGenerate.PARsp":
                        result = sMSGenerate(xmlResponse);
                        if (Setting.accountUniqueID == "")
                            nextUri = 1;
                        else
                            nextUri = 7;
                        break;
                    case "Purchase.PARsp":case "PurchaseAdivce.PARsp":
                        nextUri =4;//"resultPivot";//"/UnionPay4WP;component/PayResult.xaml";
                        result = purchase(xmlResponse);
                        break;
                    case "Authenticate.PARsp":
                        result = authenticate(xmlResponse);
                        break;
                    case "BalanceEnquiry.PARsp":
                        result = balanceEnquiry(xmlResponse);
                        break;
                    case "VersionValidation.PARsp":
                        result = versionValidation(xmlResponse);
                        break;
                }
                if (SUCCESSCODE != ServerResponseVars.TransResponseCode) result = false;
            }
            catch {
                return false;
            }
            return result;
        }
        public bool payInit(XElement xml){
            try
            {
                ServerResponseVars.TransactionType = xml.Element("cupMobile").Element("transaction").Attribute("type").Value;
                ServerResponseVars.MsgResponseCode = xml.Element("msgResponseCode").Value;
                ServerResponseVars.TransResponseCode = xml.Element("cupMobile").Element("transaction").Element("transResponseCode").Value;
                UnionPayControl.order.SessionID = xml.Element("cupMobile").Element("transaction").Element("sessionID").Value;
                OrderClass.LimitedAmount = xml.Element("cupMobile").Element("transaction").Element("limitedAmout").Value;
                //todo check responseCode and call errorTranslator
            }
            catch
            {
                return false;
            }
            return true;
        }
        public bool bankSupportEnquiry(XElement xml)
        {
            try
            {
                ServerResponseVars.TransactionType = xml.Element("cupMobile").Element("transaction").Attribute("type").Value;
                ServerResponseVars.MsgResponseCode = xml.Element("msgResponseCode").Value;
                ServerResponseVars.TransResponseCode = xml.Element("cupMobile").Element("transaction").Element("transResponseCode").Value;
                ServerResponseVars.creditBankList = xml.Element("cupMobile").Element("transaction").Element("creditBankList").Value.Split(',');
                ServerResponseVars.debitBankList = xml.Element("cupMobile").Element("transaction").Element("debitBankList").Value.Split(',');
                ServerResponseVars.prepayBankList = xml.Element("cupMobile").Element("transaction").Element("prepayBankList").Value.Split(','); 
            }  catch  { return false; }
            return true;
        }


        public bool cardInfoEnquiry(XElement xml)//这个函数需要一些，如果不对就退出的东西
        {
            
            try
            {
                ServerResponseVars.MsgResponseCode = xml.Element("msgResponseCode").Value;
                ServerResponseVars.TransResponseCode = xml.Element("cupMobile").Element("transaction").Element("transResponseCode").Value;
                IEnumerable<XElement> array = xml.Descendants("cupMobile");
                
                XElement xele = array.First();
                ServerResponseVars.TransResponseCode = xele.Element("transaction").Element("transResponseCode").Value;
                if (SUCCESSCODE != ServerResponseVars.TransResponseCode) return false;
                ServerResponseVars.cardType = xele.Element("transaction").Element("cardType").Value;
                ServerResponseVars.issuer = xele.Element("transaction").Element("issuer").Value;
                ServerResponseVars.issuerName = xele.Element("transaction").Element("issuer").Attribute("name").Value;
                
                xele = array.ElementAt(1);
                ServerResponseVars.TransResponseCode = xele.Element("transaction").Element("transResponseCode").Value;
                if (SUCCESSCODE != ServerResponseVars.TransResponseCode) return false;
                try
                {
                    ServerResponseVars.merchantRemainingAmount = xele.Element("transaction").Element("merchantRemainingAmount").Value;
                    ServerResponseVars.previousSubmitTime = xele.Element("transaction").Element("previousSubmitTime").Value;
                    ServerResponseVars.previousTransAmount = xele.Element("transaction").Element("previousTransAmount").Value;
                    ServerResponseVars.merchantLimitedAmount = xele.Element("transaction").Element("merchantLimitedAmount").Value;
                }
                catch
                {
                    try
                    {
                        ServerResponseVars.previousTransAmount = xele.Element("transaction").Element("previousTransAmount").Value;
                        ServerResponseVars.merchantLimitedAmount = xele.Element("transaction").Element("merchantLimitedAmount").Value;
                    }
                    catch
                    {
                        try
                        {
                            ServerResponseVars.merchantLimitedAmount = xele.Element("transaction").Element("merchantLimitedAmount").Value;
                        }
                        catch { }
                    }
                }
                
                
                if (3==array.Count())//如果有验证码，则取出
                {
                    xele = array.ElementAt(2);
                    ServerResponseVars.TransResponseCode = xele.Element("transaction").Element("transResponseCode").Value;
                    if (SUCCESSCODE != ServerResponseVars.TransResponseCode) return false;
                }
                
            }
            catch
            {
                return false;
            }
            Setting.issuerName = ServerResponseVars.issuerName;//settings["issuerName"] = ServerResponseVars.issuerName;
            Setting.cardType = ServerResponseVars.cardType;//settings["cardType"] = ServerResponseVars.cardType;
            Setting.LimitedAmount = ServerResponseVars.merchantRemainingAmount;//Setting.LimitedAmount = ServerResponseVars.LimitedAmout;//settings["limit"] = ServerResponseVars.merchantRemainingAmount;
            return true;
        }

     public bool sMSGenerate(XElement xml)
        {
            try
            {
                ServerResponseVars.TransactionType = xml.Element("cupMobile").Element("transaction").Attribute("type").Value;
                ServerResponseVars.MsgResponseCode = xml.Element("msgResponseCode").Value;
                ServerResponseVars.TransResponseCode = xml.Element("cupMobile").Element("transaction").Element("transResponseCode").Value;
            }
            catch
            {
                return false;
            }
            return true;
        }
       
        public bool purchase(XElement xml)
        {
            DES3 des3 = new DES3();
            
            try
            {
                ServerResponseVars.TransactionType = xml.Element("cupMobile").Element("transaction").Attribute("type").Value;
                ServerResponseVars.MsgResponseCode = xml.Element("msgResponseCode").Value;
                ServerResponseVars.TransResponseCode = xml.Element("cupMobile").Element("transaction").Element("transResponseCode").Value;
                ServerResponseVars.billAmount = xml.Element("cupMobile").Element("transaction").Element("billAmount").Value;
                ServerResponseVars.settleDate = xml.Element("cupMobile").Element("transaction").Element("settleDate").Value;
                try
                {
                    ServerResponseVars.accountUniqueID = xml.Element("cupMobile").Element("transaction").Element("accountUniqueID").Value;
                    byte[] uniqueIdByte = DES3.Hex2ByteArr(ServerResponseVars.accountUniqueID);
                    // uniqueIdByte = DES3.Hex2ByteArr2(ServerResponseVars.accountUniqueID);
                    string hexStr = des3.Decrypt40(uniqueIdByte, OrderClass.KeyDes3);
                    string uniqueIdReal = DES3.Hex2Str(hexStr);
                    Setting.accountUniqueID = uniqueIdReal.Substring(0,uniqueIdReal.Length-3);
                    
                }
                catch
                {
                   // ServerResponseVars.accountUniqueID=Setting.accountUniqueID;// ServerResponseVars.accountUniqueID = settings["accountUniqueID"].ToString();
                }
                //Setting.accountUniqueID = ServerResponseVars.accountUniqueID;//settings["accountUniqueID"] = ServerResponseVars.accountUniqueID;
            }
            catch
            {
                return false;
            }
            return true;
        }

        public bool authenticate(XElement xml) 
        {
            try{
                ServerResponseVars.TransactionType = xml.Element("cupMobile").Element("transaction").Attribute("type").Value;
                ServerResponseVars.SubmitTime= xml.Element("cupMobile").Element("submitTime").Value;
                ServerResponseVars.SessionID = xml.Element("cupMobile").Element("sessionID").Value;
                ServerResponseVars.TransSerialNumber=xml.Element("cupMobile").Element("transSerialNumber").Value;
                ServerResponseVars.TransResponseCode = xml.Element("cupMobile").Element("transaction").Element("transResponseCode").Value;
                ServerResponseVars.TransTime=xml.Element("cupMobile").Element("transTime").Value;
                ServerResponseVars.MsgResponseCode = xml.Element("msgResponseCode").Value;
            }
            catch
            {
                return false;
            }
            return true;
        }
        public bool balanceEnquiry(XElement xml) 
        {
            try
            {
                ServerResponseVars.TransactionType = xml.Element("cupMobile").Element("transaction").Attribute("type").Value;
                ServerResponseVars.TransSerialNumber = xml.Element("cupMobile").Element("transSerialNumber").Value;
                ServerResponseVars.TransResponseCode = xml.Element("cupMobile").Element("transaction").Element("transResponseCode").Value;
                ServerResponseVars.MsgResponseCode = xml.Element("msgResponseCode").Value;
                ServerResponseVars.accountBalance = xml.Element("cupMobile").Element("accountBalance").Value;
                ServerResponseVars.settleDate = xml.Element("cupMobile").Element("settleDate").Value;
            }
            catch
            {
                return false;
            }
            return true;
        }
        public bool versionValidation(XElement xml)
        {
            try
            {
                ServerResponseVars.TransactionType = xml.Element("cupMobile").Element("transaction").Attribute("type").Value;
                ServerResponseVars.TransResponseCode = xml.Element("cupMobile").Element("transaction").Element("transResponseCode").Value;
                ServerResponseVars.MsgResponseCode = xml.Element("msgResponseCode").Value;
                try
                {
                    ServerResponseVars.upgradeUrl = xml.Element("cupMobile").Element("transaction").Element("upgrade").Element("url").Value;
                    ServerResponseVars.upgradeDescription = xml.Element("cupMobile").Element("transaction").Element("upgrade").Element("description").Value;
                }
                catch
                {
                    ServerResponseVars.upgradeUrl = "";
                    ServerResponseVars.upgradeDescription = "";
                }
            }
            catch
            {
                return false;
            }
            return true;
        }

    }
}
